﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml.Linq;
using MongoDB.Driver.Builders;

namespace BattleShip_MongoDB
{
    public partial class GameRoom : Form
    {
        public GameRoom()
        {
            InitializeComponent();
        }

        private static DataTable tmpDataTable;
        private static int rowIndex = -1;

        /////////////////////////////////// *** Button click Tao Game Room *** /////////////////////////////////////

        private void buttonCreateGR_Click(object sender, EventArgs e)
        {
            // Connect to MongoDB
            MongoServer MongoDB = MongoServer.Create();
            MongoDB.Connect();

            var db = MongoDB.GetDatabase("BattleShipDataBase");

            using (MongoDB.RequestStart(db))
            {

                var collection = db.GetCollection<BsonDocument>("GameRoom");

                int iGameID = 0;
                foreach (BsonDocument item in collection.FindAll())
                {
                    String strGameID;
                    strGameID = (string)item.GetElement("GameID").Value;
                    iGameID = Convert.ToInt32(strGameID);
                    
                }
                iGameID++;

                var query = Query.Or(
                                Query.EQ("UserName1", UserInformation.UserName),
                                Query.EQ("UserName2", UserInformation.UserName)
                                );

                Boolean GameExisted = false;
                foreach (BsonDocument item in collection.Find(query))
                {
                    GameExisted = true;
                    break;
                }

                if (!GameExisted)
                {
                    UserInformation.UserName1 = UserInformation.UserName;
                    UserInformation.UserName2 = "";

                    UserInformation.gameID = Convert.ToString(iGameID);
                    BsonDocument new_user = new BsonDocument()
                        .Add("GameID", UserInformation.gameID)
                        .Add("UserName1", UserInformation.UserName)
                        .Add("UserName2", "")
                        .Add("Winer", "")
                        .Add("Status", "0");

                    collection.Insert(new_user);

                    UserInformation.isFirst = true;

                    GameForm frame = new GameForm();
                    frame.Show();
                    this.Hide();
                }
            }

            MongoDB.Disconnect();
        }

        /////////////////////////////////// *** Button click Tham gia *** /////////////////////////////////////

        private void buttonPlayGame_Click(object sender, EventArgs e)
        {
            if (rowIndex < 0) return;

            DataRow dr = tmpDataTable.Rows[rowIndex];
            UpdateTest(dr.ItemArray[0].ToString() + " " + dr.ItemArray[1].ToString());

            // Connect to MongoDB
            MongoServer MongoDB = MongoServer.Create();
            MongoDB.Connect();

            var db = MongoDB.GetDatabase("BattleShipDataBase");

            using (MongoDB.RequestStart(db))
            {
                var collection = db.GetCollection<BsonDocument>("GameRoom");

                var query = Query.Or(
                                Query.EQ("UserName1", UserInformation.UserName),
                                Query.EQ("UserName2", UserInformation.UserName)
                                );

                Boolean GameExisted = false;
                foreach (BsonDocument item in collection.Find(query))
                {
                    GameExisted = true;
                    break;
                }

                if (!GameExisted && dr[2].Equals("0"))
                {
                    var queryChoi = new QueryDocument("UserName1", dr[0].ToString());

                    BsonDocument game = collection.FindOne(queryChoi);
                    if (game != null)
                    {
                        UserInformation.UserName2 = UserInformation.UserName;
                        UserInformation.UserName1 = game["UserName1"].ToString();

                        UserInformation.gameID = game["GameID"].ToString();
                        game["UserName2"] = UserInformation.UserName;
                        game["Status"] = "0";
                        collection.Save(game);

                        UserInformation.isFirst = false;

                        GameForm frame = new GameForm();
                        frame.Show();
                        this.Hide();
                    }
                }
                else
                {
                    MessageBox.Show("Can't play game...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            MongoDB.Disconnect();
        }

        private void GameRoom_Load(object sender, EventArgs e)
        {
            labelUser.Text = "User : " + UserInformation.UserName;
            labelThang.Text = "Số trận thắng : " + UserInformation.NumberOfWin;
            labelThua.Text = "Số trận thua : " + UserInformation.NumberOfLose;
            UpdateGameRoom();
            UpdateTest("");
        }

        public void UpdateGameRoom()
        {
            tmpDataTable = new DataTable();
            DataRow dr;

            tmpDataTable.Columns.Add(new DataColumn("UserName 1", typeof(string)));
            tmpDataTable.Columns.Add(new DataColumn("UserName 2", typeof(string)));
            tmpDataTable.Columns.Add(new DataColumn("Status code", typeof(string)));
            tmpDataTable.Columns.Add(new DataColumn("Tình trạng", typeof(string)));

            // Connect to MongoDB
            MongoServer MongoDB = MongoServer.Create();
            MongoDB.Connect();

            var db = MongoDB.GetDatabase("BattleShipDataBase");

            using (MongoDB.RequestStart(db))
            {
                var collection = db.GetCollection<BsonDocument>("GameRoom");

                foreach (BsonDocument item in collection.FindAll())
                {
                    dr = tmpDataTable.NewRow();
                    dr[0] = (string)item.GetElement("UserName1").Value;
                    dr[2] = (string)item.GetElement("Status").Value;
                    if (dr[2].Equals("0"))
                    {
                        dr[1] = "";
                        dr[3] = "đang chờ user 2";
                    }
                    else if (dr[2].Equals("1"))
                    {
                        dr[1] = (string)item.GetElement("UserName2").Value;
                        dr[3] = "đang chơi";
                    }
                    else
                    {
                        dr[1] = (string)item.GetElement("UserName2").Value;
                        if (dr[2].Equals("-1"))
                            dr[3] = "đã kết thúc và user " + dr[0] + " thắng";
                        else
                            dr[3] = "đã kết thúc và user " + dr[1] + " thắng";
                    }
                    tmpDataTable.Rows.Add(dr);
                }
            }

            MongoDB.Disconnect();
            // End Connect to MongoDB

            dataGridViewGR.DataSource = tmpDataTable;
            dataGridViewGR.AllowUserToAddRows = false;
            rowIndex = -1;
        }

        private void GameRoom_FormClosed(object sender, FormClosedEventArgs e)
        {
            UserInformation.LogOut();
            Application.Exit();
        }

        private void dataGridViewGR_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            rowIndex = dataGridViewGR.CurrentCell.RowIndex;
            UpdateTest(rowIndex);
        }

        private void UpdateTest(Object test)
        {
            if (UserInformation.isTest)
                labelTest.Text = test.ToString();
            else
                labelTest.Text = "";
        }
        
    }
}
